package cn.edu.zut.internship.service.impl.sys;


import cn.edu.zut.internship.bean.sys.Result;
import cn.edu.zut.internship.bean.sys.SysUser;
import cn.edu.zut.internship.entity.AuthSysPermission;
import cn.edu.zut.internship.entity.AuthSysRole;
import cn.edu.zut.internship.entity.AuthSysUser;
import cn.edu.zut.internship.iservice.notify.NotifySV;
import cn.edu.zut.internship.iservice.sys.IPermissionService;
import cn.edu.zut.internship.iservice.sys.IUserService;
import cn.edu.zut.internship.mapper.setting.SettingMapper;
import cn.edu.zut.internship.mapper.student.StudentMapper;
import cn.edu.zut.internship.mapper.sys.AuthSysRoleMapper;
import cn.edu.zut.internship.mapper.sys.AuthSysUserMapper;

import cn.edu.zut.internship.mapper.sys.UserMapper;
import cn.edu.zut.internship.mapper.teach.TeachMapper;
import cn.edu.zut.internship.utils.PrimaryKeyUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private AuthSysUserMapper userMapper;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private AuthSysRoleMapper roleMapper;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    PrimaryKeyUtil primaryKeyUtil;
    @Autowired
    TeachMapper teachMapper;
    @Autowired
    UserMapper userMapper1;
    @Autowired
    NotifySV notifySV;
    @Autowired
    SettingMapper settingMapper;
    @Override
    public AuthSysUser findByUserName(String username) {
        //查询用户信息
        AuthSysUser authSysUser = userMapper.selectByUserName(username);
        //查询用户角色信息
        List<AuthSysRole> authSysRoles = roleMapper.selectByUrId(authSysUser.getUrId());
        authSysUser.setRoleList(authSysRoles);
        return authSysUser;
    }

    @Override
    public SysUser getSysUserByAccount(String account) {
        SysUser sysUserByAccount = userMapper1.getSysUserByAccount(account);
        if(sysUserByAccount !=null) {
            //查询用户角色信息
            List<AuthSysRole> authSysRoles = roleMapper.selectByUrId(sysUserByAccount.getUserId());
            sysUserByAccount.setRoleList(authSysRoles);
            Set<Long> roles = new HashSet<>();
            for (AuthSysRole authSysRole : authSysRoles) {
                roles.add(authSysRole.getRlId());
            }
            sysUserByAccount.setRoles(roles);
            //查询用户未读消息总数
            int notifyNum = (int) notifySV.getNotifyNum(account).getBean().get("notifyNum");
            sysUserByAccount.setNotifyNum(notifyNum);
            return sysUserByAccount;
        }
        return null;
    }

    @Override
    public Result findAll(Map params) {
        Result result = new Result();
        //获取当前学期
        Map semester = settingMapper.getSetting("currentSemester");
        String nowSemester = (String) semester.get("settingValue");
        params.put("semester",nowSemester);
        String userType = (String) params.get("userType");
        List<Map> userList = new ArrayList<>();
        int total = 0;
        if(StringUtils.isEmpty(userType)) {
            userList = userMapper.selectAll(params);
            total = userMapper.selectAllTotal(params);
        }else if(userType.equals("2")){
            userList = studentMapper.selectStudent(params);
            total = studentMapper.selectStudentCount(params);
        }else{
            userList = userMapper.selectAll(params);
            total = userMapper.selectAllTotal(params);
        }

        for(Map map : userList){
            if("0".equals(map.get("userType"))){
                map.put("userType","管理员");
            }else if("1".equals(map.get("userType"))){
                map.put("userType","教师");
            }else if("2".equals(map.get("userType"))){
                map.put("userType","学生");
            }else {
                map.put("userType","未定义");
            }
        }
        //查询用户的角色信息
        for(Map user : userList){
            List<Map> roles = userMapper.selectRoleListByUserId((Long) user.get("userId"));
            user.put("roleList",roles);
        }
        result.setBeans(userList);
        result.getBean().put("total",total);
        return result;
    }

    @Override
    public void assignUserRoles(Map user) {
        Long userId = (Long) user.get("userId");
        //删除原有用户角色关联信息
        this.userMapper.unassignRoles(userId);
        List<Map> roleList = (List<Map>) user.get("roleList");
        for(Map role:roleList) {
            Long roleId;
            if(role.get("sysRoleId") instanceof Integer){
                roleId = new Long((Integer)role.get("sysRoleId"));
                role.put("sysRoleId",roleId);
            }else {
                roleId =  (Long) role.get("sysRoleId");
            }
            this.userMapper.assignRole(userId, (Long) role.get("sysRoleId"));
        }
    }

    @Override
    public List<String> getUserPermssions(String username) {
        List<String> permList = null;

        List<AuthSysPermission> permissionList = this.permissionService.searchUserPermissions(username);
        if(permissionList != null){
            permList = new ArrayList<>();
            for(AuthSysPermission perm:permissionList){
                permList.add(perm.getResources().getRscUrl()+":"+perm.getOperator().getOptUrl()+":*");
            }
        }
        return permList;
    }
    @Override
    public SysUser getSysUserInfo(String username){
        SysUser sysUserInfo = userMapper.getSysUserInfo(username);
        return sysUserInfo;
    }

    @Override
    public Result addUser(Map params) {
        Result result = new Result();
        String userType = (String) params.get("userType");
        if ("0".equals(userType)) {
            //新增管理员信息
            Long userId = primaryKeyUtil.generatePrimaryKey("sys_user");
            params.put("userId",userId);
            params.put("userAccount",params.get("jobNumber"));
            params.put("userPhone",params.get("teachPhone"));
            params.put("userName",params.get("name"));
            params.put("userPwd",params.get("teachPhone"));
            params.put("sex",params.get("teachGender"));
            userMapper1.addUser(params);
            //绑定角色
            userMapper.assignRole(userId,1L);
        }else if("1".equals(userType)){
            //新增用户信息
            Long userId = primaryKeyUtil.generatePrimaryKey("sys_user");
            params.put("userId",userId);
            params.put("userAccount",params.get("jobNumber"));
            params.put("userPhone",params.get("teachPhone"));
            params.put("userName",params.get("name"));
            params.put("userPwd",params.get("teachPhone"));
            params.put("sex",params.get("teachGender"));
            userMapper1.addUser(params);
            //新增教师信息
            Long teachId = primaryKeyUtil.generatePrimaryKey("teach");
            params.put("teachId",teachId);
            teachMapper.addTeach(params);
            //绑定角色
            userMapper.assignRole(userId,2L);
        }else if("2".equals(userType)){
            //获取当前学期
            Map semester = settingMapper.getSetting("currentSemester");
            String nowSemester = (String) semester.get("settingValue");
            params.put("semester",nowSemester);
            //新增用户信息
            Long userId = primaryKeyUtil.generatePrimaryKey("sys_user");
            params.put("userId",userId);
            params.put("userAccount",params.get("studentNumber"));
            params.put("userPhone",params.get("studentPhone"));
            params.put("userName",params.get("name"));
            params.put("userPwd",params.get("studentPhone"));
            params.put("sex",params.get("studentGender"));
            userMapper1.addUser(params);
            //新增学生信息
            Long studentId = primaryKeyUtil.generatePrimaryKey("student");
            params.put("studentId",studentId);
            studentMapper.addStudent(params);
            //绑定角色
            userMapper.assignRole(userId,3L);
        }
        return result;
    }

    @Override
    public Result deleteUser(Map params) {
        Result result = new Result();
        //删除用户
        userMapper1.deleteUser(params);
        //删除关联角色
        userMapper.unassignRoles((Long) params.get("userId"));
        return result;
    }

    @Override
    public Result updateUser(Map params) {
        Result result = new Result();
        userMapper1.updateUser(params);
        return result;
    }

    @Override
    public Result getUser(Map params) {
        Result result = new Result();
        Map user = userMapper1.getUser(params);
        result.setBean(user);
        return result;
    }

    @Override
    public Result getUserReportInfo(Map params) {

        return null;
    }
}
